package twitter.Server;

import java.net.ServerSocket;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import twitter.TwitterLibrary.SocketConfig;
import twitter.TwitterLibrary.Utility;

import Muilticast.MulticastNoticeSender;
import Muilticast.MulticastReceiver;
import Twitter.Listener.RequestListener;
import Twitter.Listener.ShutDownListener;
/************************************************
 * this class is designed for generic server
 * @author fang
 *
 */
public class Server {

	
	protected MulticastReceiver multicastReceiver;
	protected MulticastNoticeSender multicastSender;
	protected Random r;
	protected Utility utility;
	protected final ReentrantReadWriteLock rwl= new ReentrantReadWriteLock();
	/****************************************
	 * Class constructor
	 */
	public Server()
	{
		r=new Random();
		SocketConfig.identifier=r.nextInt();
		utility=new Utility(rwl);
	
		multicastSender=new MulticastNoticeSender(utility);
		multicastReceiver=new MulticastReceiver(utility);
		SocketConfig.identifierToServer=new HashMap<String,String>();
		SocketConfig.serverToType=new HashMap<String,ServerType>();
		
	}
	/***********************************
	 * start the server
	 * @param end
	 * @param port
	 */
	public void startServer(String end,int port) {
		
		RequestListener listener=new RequestListener(rwl,utility.threadPool,utility);		
		listener.listenToSocket(port);
		
		ServerSocket serverSocket=listener.getServerSocket();
		
		utility.threadPool.execute(multicastReceiver);
		utility.threadPool.execute(multicastSender);
		
		ShutDownListener shutdownListener=new ShutDownListener(serverSocket,utility.threadPool,listener);
		utility.threadPool.execute(shutdownListener);
		
		listener.catchRequest();
	
		
		//if(SocketConfig.serverType!=ServerType.PrimaryServer)
		//{
			
			
		//}
		
	}

}
